package com.example.chatgptapplication.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chatgptapplication.entity.Admin;
import com.example.chatgptapplication.mapper.AdminMapper;
import com.example.chatgptapplication.service.AdminService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;


@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {


    @Override
    public Admin adminLogin(String username, String password) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",password);
        Admin admin = getOne(queryWrapper);
//        UserHolder.saveUser(admin);
        return admin;
    }

    @Override
    public Admin createAdmin(Admin admin) {
        if(!ObjectUtils.isEmpty(getOne(admin.getUsername()))){
            return null;
        }
        admin.setCreateTime(new Date());
        admin.setUpdateTime(new Date());
        if(ObjectUtils.isEmpty(admin.getAvatar())){
            //设置默认头像
            admin.setAvatar("http://localhost:8080/avater.png");
        }
        admin.setStatus(1);
        this.save(admin);
        return admin;
    }

    @Override
    public Page<Admin> getAdminPageData(Admin adminDTO) {
        Page<Admin> adminDTOPage = getPageData(adminDTO);
        QueryWrapper<Admin> queryWrapper = getQueryData(adminDTO);
        return this.page(adminDTOPage,queryWrapper);
    }

    @Override
    public Admin getOne(String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return this.getOne(queryWrapper);
    }

    @Override
    public void updateAdmin(Admin admin) {
        this.updateById(admin);
    }

    @Override
    public void deleteAdmin(Admin admin) {
        this.removeById(admin);
    }


    public Page<Admin> getPageData(Admin adminDTO){
        Integer pageNum = adminDTO.getPageNum();
        Integer pageSize = adminDTO.getPageSize();
        Page<Admin> page = new Page<>(pageNum,pageSize);
        return page;
    }


    public QueryWrapper<Admin> getQueryData(Admin adminDTO){
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        if(adminDTO.getUsername() != null && !adminDTO.getUsername().equals("")){
            queryWrapper.eq("username",adminDTO.getUsername());
        }
        return queryWrapper;
    }
}
